/**
 * API响应处理工具
 * 统一处理API响应数据格式转换和错误处理
 */

import { constants } from '../api'

/**
 * 统一的API响应处理
 * @param {Promise} apiCall - API调用Promise
 * @param {Object} options - 配置选项
 * @returns {Promise} 处理后的响应
 */
export const handleApiResponse = async (apiCall, options = {}) => {
  const {
    showLoading = false,
    showError = true,
    loadingText = '加载中...',
    successCallback = null,
    errorCallback = null
  } = options

  if (showLoading) {
    uni.showLoading({
      title: loadingText,
      mask: true
    })
  }

  try {
    const response = await apiCall
    
    if (showLoading) {
      uni.hideLoading()
    }

    if (response.code === '1000') {
      if (successCallback) {
        successCallback(response.result)
      }
      return {
        success: true,
        data: response.result,
        message: response.message
      }
    } else {
      const errorMsg = response.message || '请求失败'
      if (showError) {
        uni.showToast({
          title: errorMsg,
          icon: 'error'
        })
      }
      if (errorCallback) {
        errorCallback(errorMsg)
      }
      return {
        success: false,
        data: null,
        message: errorMsg
      }
    }
  } catch (error) {
    if (showLoading) {
      uni.hideLoading()
    }
    
    console.error('API调用失败:', error)
    const errorMsg = '网络连接失败'
    
    if (showError) {
      uni.showToast({
        title: errorMsg,
        icon: 'error'
      })
    }
    
    if (errorCallback) {
      errorCallback(errorMsg)
    }
    
    return {
      success: false,
      data: null,
      message: errorMsg
    }
  }
}

/**
 * 教师数据格式转换
 * 将API返回的教师数据转换为UI组件需要的格式
 */
export const formatTeacherData = (apiData) => {
  if (!apiData) return {}
  
  return {
    id: apiData.id,
    name: apiData.nickname,
    nickname: apiData.nickname,
    avatar: apiData.avatar || '/static/logo.png',
    verified: apiData.verified || false,
    school: apiData.highestEducationSchool,
    degree: constants.TEACHER_LEVEL_TEXT[apiData.educationLevel] || '未知',
    major: apiData.major,
    orders: apiData.tutoringCount || 0,
    tutoringCount: apiData.tutoringCount || 0,
    desc: apiData.selfIntroduction || apiData.experience || '',
    selfIntroduction: apiData.selfIntroduction,
    experience: apiData.experience,
    canHelp: formatGoodAtItems(apiData.goodAtItems),
    goodAtItems: apiData.goodAtItems,
    educationLevel: apiData.educationLevel,
    highestEducationSchool: apiData.highestEducationSchool,
    rating: apiData.score || 0,
    score: apiData.score || 0,
    commentList: apiData.commentList || []
  }
}

/**
 * 订单数据格式转换
 * 将API返回的订单数据转换为UI组件需要的格式
 */
export const formatOrderData = (apiData) => {
  if (!apiData) return {}
  
  return {
    id: apiData.id,
    no: apiData.orderNo,
    orderNo: apiData.orderNo,
    date: apiData.createTime,
    createTime: apiData.createTime,
    type: constants.TUTORING_ITEM_TEXT[apiData.tutoringItem] || '未知',
    tutoringItem: apiData.tutoringItem,
    budget: formatBudget(apiData.budgetMin, apiData.budgetMax),
    budgetMin: apiData.budgetMin,
    budgetMax: apiData.budgetMax,
    signupCount: apiData.deliverCount || apiData.deliveryCount || 0,
    deliverCount: apiData.deliverCount || 0,
    deliveryCount: apiData.deliveryCount || 0,
    avatarList: apiData.avatarList || [],
    studentName: apiData.studentName,
    major: apiData.studyMajor,
    studyMajor: apiData.studyMajor,
    studySchool: apiData.studySchool,
    studyStage: apiData.studyStage,
    studyPlace: apiData.studyPlace,
    teacherLevel: apiData.teacherLevel,
    teacherAbroad: apiData.teacherAbroad,
    requirementText: apiData.requirementText,
    comment: apiData.comment,
    description: apiData.requirementText,
    extra: apiData.comment,
    modifyBtnShow: apiData.modifyBtnShow || false
  }
}

/**
 * 格式化擅长项目
 */
export const formatGoodAtItems = (goodAtItems) => {
  if (!Array.isArray(goodAtItems)) return []
  return goodAtItems.map(item => constants.GOOD_AT_ITEMS_TEXT[item]).filter(Boolean)
}

/**
 * 格式化预算区间
 */
export const formatBudget = (min, max) => {
  if (!min || !max) return '面议'
  return `${min}-${max}元`
}

/**
 * 格式化时间
 */
export const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return timeStr
  }
}

/**
 * 分页数据处理
 */
export const handlePaginationData = (response, currentList = [], isRefresh = false) => {
  if (!response || !response.result) {
    return {
      list: currentList,
      pagination: {
        current: 1,
        size: 10,
        total: 0,
        hasMore: false
      }
    }
  }

  const result = response.result
  const newRecords = result.records || []
  
  return {
    list: isRefresh ? newRecords : [...currentList, ...newRecords],
    pagination: {
      current: result.current || 1,
      size: result.size || 10,
      total: result.total || 0,
      pages: result.pages || 0,
      hasMore: (result.current || 1) < (result.pages || 0)
    }
  }
}

/**
 * 常用的错误处理
 */
export const commonErrorHandler = {
  // 网络错误
  networkError: () => {
    uni.showToast({
      title: '网络连接失败，请检查网络设置',
      icon: 'none',
      duration: 2000
    })
  },
  
  // 参数错误
  paramError: () => {
    uni.showToast({
      title: '参数错误，请重试',
      icon: 'none'
    })
  },
  
  // 未授权
  unauthorized: () => {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    // 可以在这里跳转到登录页面
  },
  
  // 服务器错误
  serverError: () => {
    uni.showToast({
      title: '服务器繁忙，请稍后重试',
      icon: 'none'
    })
  }
}

export default {
  handleApiResponse,
  formatTeacherData,
  formatOrderData,
  formatGoodAtItems,
  formatBudget,
  formatTime,
  handlePaginationData,
  commonErrorHandler
}
